package com.wang.wx.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class DynamicDataSplitter {

    private static final int BATCH_SIZE = 100000; // 每批处理的数据行数
    private static final AtomicInteger fileCounter = new AtomicInteger(0); // 用于文件编号
    private static final AtomicInteger currentLine = new AtomicInteger(0); // 当前行数，用于线程间同步
    private static final BufferedReader reader; // 共享的文件读取器

    static {
        try {
            reader = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\Downloads\\script\\script.sql"), StandardCharsets.UTF_16));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        ExecutorService executor = Executors.newFixedThreadPool(5);

        for (int i = 0; i < 5; i++) {
            executor.submit(DynamicDataSplitter::processLines);
        }

        executor.shutdown();
        try {
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static void processLines() {
        try {
            while (true) {
                StringBuilder sb = new StringBuilder();
                int linesRead = 0;

                synchronized (reader) { // 确保每次只有一个线程读取文件
                    while (linesRead < BATCH_SIZE) {
                        String line = reader.readLine();
//                        currentLine.incrementAndGet();
//                        if (currentLine.get() == 359629) {
//                            log.info("当前行数：{}", currentLine.get());
//                        }
                        if (line == null) {
                            break; 
                        }

                        sb.append(line).append("\n");
                        linesRead++;
                    }
                }

                if (linesRead == 0) {
                    break; // 文件末尾或所有行已处理
                }

                writeToFile(sb.toString(), fileCounter.getAndIncrement());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writeToFile(String content, int fileCount) {
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("C:\\script\\script\\" + fileCount + ".txt"), StandardCharsets.UTF_16))) {
            writer.write(content);
            log.info("写入文件：{}", fileCount);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}